<template>
	<div>
		<div style="border: 1px solid #ccc; margin-top: 10px">
			<Toolbar :default-config="toolbarConfig" :editor="editorRef" :mode="mode" style="border-bottom: 1px solid #ccc" />
			<Editor v-model="valueHtml" :default-config="editorConfig" :mode="mode" style="overflow-y: hidden" :style="styles" @onChange="handleChange" @onCreated="handleCreated" />
		</div>
	</div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, reactive, toRefs, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import global from '@/utils/global'
export default {
	components: { Editor, Toolbar },
	props: {
		modelValue: {
			type: String,
			default: '',
		},
		height: {
			type: String,
			default: '500px',
		},
		mode: {
			type: String,
			default: 'default', // default simple
		},
		imagePreview: {
			type: String,
			default: '',
		},
		url: {
			type: String,
			default: '',
		},
	},
	emits: ['update:modelValue'],
	setup(props, context) {
		console.log(props.url)
		// 编辑器实例，必须用 shallowRef，重要！
		const editorRef = shallowRef()
		// 内容 HTML
		const state = reactive({
			valueHtml: props.modelValue,
			styles: {
				height: props.height,
			},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {},
			},
		})
		watch(
			() => props.modelValue,
			value => (state.valueHtml = value)
		)
		const toolbarConfig = {
			excludeKeys: ['group-video', 'uploadVideo', 'insertVideo', 'emotion'],
		}
		state.editorConfig.MENU_CONF['uploadImage'] = {
			customUpload(file, insertFn) {
				const formData = new FormData()
				formData.append('file', file)
				global.$fetchUploadFile(props.url, formData).then(data => {
					if (data.code == 200) {
						insertFn(`${data.data.url}`, data.data.fileName, '')
					}
				})
			},
		}

		// 组件销毁时，也及时销毁编辑器，重要！
		onBeforeUnmount(() => {
			const editor = editorRef.value
			if (editor == null) return

			editor.destroy()
		})

		// 编辑器回调函数
		const handleCreated = editor => {
			editorRef.value = editor // 记录 editor 实例，重要！
		}
		const handleChange = editor => {
			context.emit('update:modelValue', editor.getHtml())
		}

		return {
			...toRefs(state),
			editorRef,
			toolbarConfig,
			handleCreated,
			handleChange,
		}
	},
}
</script>
<style lang="scss" scoped>
:deep() {
	.w-e-full-screen-container {
		z-index: 99999;
		.w-e-bar-show {
			justify-content: center;
		}
	}
}
</style>
